/*
 * $Id: AssetReRegistrationController.java,v 1.5 2012/04/29 21:59:35 navdeep_mahajan Exp $
 * 
 * Copyright (C) 2010 General Electric Company. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of the General
 * Electric Company (GE). You shall not disclose this software and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with GE.
 * 
 * GE MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT. GE SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING, OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES.
 */

package com.ge.healthcare.autosc.ui.assetReg.web;

import java.util.ArrayList;
//import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.ge.healthcare.autosc.common.ASCLogger;
import com.ge.healthcare.autosc.ui.assetReg.common.AssetRegConstants;
import com.ge.healthcare.autosc.ui.assetReg.domain.SblAssetRegFailRec;
import com.ge.healthcare.autosc.ui.assetReg.exceptions.AssetRegisterException;
import com.ge.healthcare.autosc.ui.assetReg.service.FailureRecordManager;
import com.ge.healthcare.autosc.ui.assetReg.service.AssetRegistrationHelper.RegistrationType;
import com.ge.med.service.eds.commons.DataException;
import com.ge.med.service.eds.commons.ResourceException;
import com.gehc.service.auth.Authorization;
import com.gehc.service.auth.AuthorizationFactory;
import com.gehc.service.auth.ControlledObject;
import com.gehc.service.auth.Group;
import com.gehc.service.auth.Role;

public class AssetReRegistrationController implements Controller {

	FailureRecordManager failureRecordMananger;

	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		//final String methodName = "handleRequest";
		List<SblAssetRegFailRec> failureRecords = new ArrayList<SblAssetRegFailRec>();
		Map<String, Object> myModel = new HashMap<String, Object>();
		String registerRequestStatus = null;
		int pageCount = 0;
		
		String searchSysId = request.getParameter("searchSysId");
		String reRegisterSysId = request.getParameter("registerSysId");

		// Fetch the uid from the session
		String ssoUID = (String) request.getHeader("sso_uid");
		/*ASCLogger.info(this.getClass(), methodName, String.format("<<ssoUID test2:%s", ssoUID));

		Enumeration headersEnum = request.getHeaderNames();
        while ( headersEnum.hasMoreElements()){
        String header = (String)headersEnum.nextElement();
        ASCLogger.info(this.getClass(), methodName, String.format("%s:%s", header, (String)request.getHeader(header)));
        }*/
		
		request.setAttribute("noRecords", false);
		request.setAttribute("regFail", false);

		// Handle Registration request for an ID
		if (reRegisterSysId != null) {
			 try {
				 SblAssetRegFailRec record = new SblAssetRegFailRec();
				 record.setSystemId(reRegisterSysId);
				failureRecordMananger.registerAndRemoveRecord(record, RegistrationType.IndividualRegistration);
				searchSysId = null;
				registerRequestStatus = "Registration Successful for SystemId = "
						+ reRegisterSysId
						+ " and Record Removed from Failure Table";
			} catch (Exception e) {
				registerRequestStatus = "Registration Failed for SystemId = "
					+ reRegisterSysId + " Error Msg: "
					+ e.getMessage();
			request.setAttribute("regFail", true);
			} 

		}

		// Handle Search request for an ID
		if (searchSysId != null) {
			SblAssetRegFailRec failureRecord =null;
			try {
				failureRecord = this.failureRecordMananger
						.getFailureRecord(searchSysId);
				if (failureRecord == null) {
					registerRequestStatus = "No Record Found for SystemId = "
							+ searchSysId;
					request.setAttribute("noRecords", true);
				} else
					failureRecords.add(failureRecord);
			} catch (AssetRegisterException e) {
				registerRequestStatus = "No Record Found for SystemId = "
					+ searchSysId+"Exception: "+e.getMessage();
			request.setAttribute("noRecords", true);
			}
			
			request.setAttribute("pageCount", 1);
			request.setAttribute("search", true);
		}

		// Display List of all system IDs if request is not of searching an ID
		if (searchSysId == null) {
			int pageNo = request.getParameter("page") == null ? 1 : Integer
					.parseInt(request.getParameter("page"));
			try{
			List<SblAssetRegFailRec> allRecords = failureRecordMananger
					.getAllFailureRecords();
			if (allRecords == null || allRecords.size() == 0) {
				registerRequestStatus = "No failure record exist";
				request.setAttribute("noRecords", true);
			} else {
				failureRecords = new ArrayList<SblAssetRegFailRec>();
				for (int recordNo = (pageNo - 1) * 10; recordNo < allRecords
						.size()
						&& recordNo < (pageNo - 1) * 10 + 10; ++recordNo)
					failureRecords.add(allRecords.get(recordNo));
				pageCount = allRecords.size() / 10;
				if ((allRecords.size() % 10) > 0) {
					pageCount++;
				}
			}
			}catch (AssetRegisterException e) {
				registerRequestStatus = "Unable to get failure records: "+e.getMessage();
				request.setAttribute("noRecords", true);
			}
			request.setAttribute("pageCount", pageCount);
			request.setAttribute("search", false);
		}

		List<String> _groupNames = getAllUserGroup();
		request.setAttribute("groupNames", _groupNames);
		myModel.put("groupNames", _groupNames);
        
		//TODO-Need to Integrate with the latest EPS interface
//		if(ssoUID!=null){
//			List<String> _groupNames = getUserGroup(ssoUID);
//			request.setAttribute("groupNames", _groupNames);
//			myModel.put("groupNames", _groupNames);
//		}
		
		myModel.put("failureRecs", failureRecords);
		myModel.put("registerRequestStatus", registerRequestStatus);

		return new ModelAndView("srchSysId", "model", myModel);
	}

	public ModelAndView handleRenderRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		// fetch the uid from the session
		String ssoUID = (String) request.getHeader("sso_uid");
		List<SblAssetRegFailRec> failureRecords = failureRecordMananger
				.getAllFailureRecords();
		Map<String, Object> myModel = new HashMap<String, Object>();
		String registerRequestStatus = null;

		myModel.put("failureRecs", failureRecords);
		myModel.put("registerRequestStatus", registerRequestStatus);

		//List<String> _groupNames = getAllUserGroup();
		List<String> _groupNames = getUserGroup(ssoUID);

		myModel.put("groupNames", _groupNames);

		return new ModelAndView("srchSysId", "model", myModel);
	}

	public FailureRecordManager getFailureRecordMananger() {
		return failureRecordMananger;
	}

	public void setFailureRecordMananger(
			FailureRecordManager failureRecordMananger) {
		this.failureRecordMananger = failureRecordMananger;
	}

	/**
	 * Temporary method to return all the roles.
	 * 
	 * @param ssoId
	 * @return
	 */
	private List<String> getAllUserGroup() {
		List<String> groupNamesList = new ArrayList<String>();
		groupNamesList.add(AssetRegConstants.BATCH_UPDATER_ROLE);
		groupNamesList.add(AssetRegConstants.ASSET_REGISTRAR_ROLE);
		groupNamesList.add(AssetRegConstants.INDIVIDUAL_UPDATER_ROLE);
		return groupNamesList;
	}

	private List<String> getUserGroup(String ssoId) {
		List<String> groupNamesList = new ArrayList<String>();
		Authorization auth = AuthorizationFactory.getDefaultInstance()
				.getAuthorizationObject();
		String _groupName = null;
		String _roleName = null;
		try {
			Group group = new Group();
			
			group.setAppspecificid(ssoId);

			Map result = auth.getControlledObjects(AssetRegConstants.APP_NAME,
					group);

			//ASCLogger.info(this.getClass(), "getUserGroup", String.format("<<No of authObjects:%s", result.size()));
			Integer _size = 0;

			if (result.size() > 0) {
				Set keySet = result.keySet();
				Iterator keySetItr = keySet.iterator();

				Set featureKeySet = null;
				Role role = null;
				ControlledObject cObj = null;
				String appSpecID = null;
				String cObjName = null;
				String rolesName = null;
				Set controlledObjKeySet = null;
				Iterator controlledObjKeySetIterator = null;

				Map value = null;

				while (keySetItr.hasNext()) {
					role = (Role) keySetItr.next();
					value = (Map) result.get(role);

					controlledObjKeySet = value.keySet();
					controlledObjKeySetIterator = controlledObjKeySet
							.iterator();

					while (controlledObjKeySetIterator.hasNext()) {

						cObj = (ControlledObject) controlledObjKeySetIterator
								.next();
						appSpecID = cObj.getAppspecificid();

						if (cObj.getParentid() != 0) {
							cObjName = appSpecID.substring(appSpecID
									.lastIndexOf('/') + 1);
							rolesName = appSpecID.substring(0, appSpecID
									.indexOf('/'));
						} else {
							cObjName = appSpecID;
							rolesName = appSpecID;
						}

						_roleName = role.getName();
						
						groupNamesList.add(_roleName);
					}
				}
			}

			return groupNamesList;
		}

		catch (DataException e) {
			// TODO Auto-generated catch block
			ASCLogger.error("Caught DataException", e);
			// e.printStackTrace();
		} catch (ResourceException e) {
			// TODO Auto-generated catch block
			ASCLogger.error("Caught ResourceException", e);
			// e.printStackTrace();
		}

		return groupNamesList;
	}
}
